<?php
/*
 *
 * Copyright (c) 2009 Doubleclique (cameron [at] doubleclique [dot] com)
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license
 *
 */

/**
 *
 * simple-sitemap
 *
 * @name     simple-sitemap
 * @version  0.2
 * @author   Cam Spiers (camspiers [at] gmail [dot] com)
 *
 */
class SimpleSitemap extends Controller
{

	const YEARLY	= 'yearly';
	const MONTHLY	= 'monthly';
	const WEEKLY	= 'weekly';
	const DAILY	= 'daily';
	const HOURLY	= 'hourly';
	const ALWAYS	= 'always';
	
	protected $_urls = false;

	static $cache_file = '../sitemap.xml';
	
	public function Urls()
	{

		if (!$this->_urls) {

			$this->_urls = new DataObjectSet();

			$implementerClasses = ClassInfo::implementorsOf('SitemapResourceInterface');

			$resources = new DataObjectSet();

			if (is_array($implementerClasses)) {

				foreach ($implementerClasses as $class) {

					$objects = DataObject::get($class);

					if ($objects instanceof DataObjectSet && $objects->TotalItems() > 0) {

						$resources->merge($objects);

					}
					
				}
			}
			
			foreach ($resources as $resource) {
				
				if ($resource->SitemapUrlShow()) {

					$resource->SitemapUrlPriority = $resource->SitemapUrlPriority();

					$this->_urls->push($resource);

				}
			}

			$this->_urls->sort('SitemapUrlPriority', 'DESC');
			
		}

		return $this->_urls;
	}
	
	public function index()
	{

		ContentNegotiator::disable();
		
		SSViewer::set_source_file_comments(false);

		$this->getResponse()->addHeader('Content-Type', 'application/xml; charset="utf-8"');
		
		return array();

	}

	public function cache()
	{

		ob_start();
		
		Director::direct('/sitemap.xml');

		file_put_contents(self::$cache_file, ob_get_clean());
		
	}

}